const Interesting = require("../model/interesting.js");
const logger = require('../utils/logger')
const {transPromise, cPromise} = require('../utils/myPromise')
const {host} = require('../config')
const Promise = require('bluebird')
const crawlRestaurant = require('./crawlRestaurant')
const {translateUrlToAbsolute} = require('../utils')
const totalInfoHandle = require('../utils/totalInfoHandle')

/**
 * 上传图片到七牛
 * @type {UploadFile}
 */
const {UploadFiles} = require('../utils/upload')

const getContentTrans = (result, url) => {
  return new Promise((resolve, reject) => {
	  // let contentTransArr = []
	  // let contentTransIdx = []
	  // result.content.forEach((v, k) => {
		 //  let tag = v.tag
		 //  if (tag === 'p') {
			//   contentTransArr.push(transPromise(v.text, url))
			//   contentTransIdx.push(k)
		 //  }
    //
		 //  if (tag === 'h2') {
			//   contentTransArr.push(transPromise(v.text, url))
			//   contentTransIdx.push(k)
		 //  }
    //
		 //  if (tag === 'figure') {
			//   contentTransArr.push(transPromise(v.text, url))
			//   contentTransIdx.push(k)
		 //  }
	  // })
    //
	  // Promise.all(contentTransArr).then(res => {
		 //  // console.dir(res)
		 //  res.forEach((v, k) => {
			//   if (result.content[contentTransIdx[k]].text) result.content[contentTransIdx[k]].text = v
		 //  })
		 //  resolve(result.content)
	  // })
    (async () => {
      try {
        let newContent = []
        for(let v of result.content) {
          let tag = v.tag

          if (tag !== 'div') {
            let text = await transPromise(v.text)
            newContent.push({
              ...v,
              text
            })
          } else {
            let newImgs = []
            for(let img of v.imgs) {
              newImgs.push({
                ...img,
                textCn: await transPromise(img.text)
              })
            }
            newContent.push({
              ...v,
              imgs:newImgs
            })
          }
        }
        resolve(newContent)
      } catch (e) {
        logger.error(e)
      }
    })()

  })

}

const uploadInterestingImags = (result, cb) => {
  let imgs = []
  let imgsUploads = []

  imgs.push({src: result.mainPic.src})

  result.content.forEach(value => {
    if (value.tag === 'figure') {
      imgs.push({
        src: value.src
      })
    }

    if (value.tag === 'div') {
      value.imgs.forEach(value => {
        imgs.push({
          src: value.src
        })
      })
    }
  })

  logger.info('uploading insteresting imgs', result.url)

  imgs.map(item => {
    let resUrl = ''
    if (item.src) {
      resUrl = translateUrlToAbsolute(item.src, host)
      imgsUploads.push({
        resUrl,
        key: resUrl.split('/').pop()
      })
    } else {
      logger.error('upload insteresting imgs src error!!!', JSON.stringify(item), result.url)
    }
  })

  UploadFiles(imgsUploads)

}


module.exports = (url, {regionId = ''}) => {
  logger.info(`crawling ineresting  ${url}`)
  totalInfoHandle.add({
    type: 0,
    url,
    regionId
  })
	return new Promise(function (resolve, reject) {
		cPromise(url)
			.then(async $$ => {
				try {
					let result = {
						url,
						gathered: false,
						mainPic: {
							title: $$('._3zrgJ46ouVPVD8zWaHX0l6 img').attr('title'),
							src: $$('._3zrgJ46ouVPVD8zWaHX0l6 img').attr('src'),
						}, // 主图
						title: {
							text: $$('._2AoqKUcdJHPd7RfPOmH1IW h1').text(),
							intro: $$('._2OpAl6NVxwk6F-NHqx4crJ ._2WVT_e39nAf0U6u77zRdcu').text(),
							time: $$('._2OpAl6NVxwk6F-NHqx4crJ ._1wBHFCdy5D4YZ-bDtYQxb_').text(),
						},
						content: [], // 内容
						map: {
							name: $$('._1MB1vj7GPnORlUNcPA-jBj').text(),
							location: $$('._3Ca2TqwtDlEJcEZrmPbZ_W ._3YPfNh8cCEjUf8VEeesPXU').html()
						}, // 位置
						restaurantInfo: {
							url: $$('.mDzrpt8-rCS6ii8XNKfHx').attr('href'),
							name: $$('.mDzrpt8-rCS6ii8XNKfHx').text(),
							tel: $$('._22RPGW_BfwZHRqx70--LbL').text().split(':')[1],
							addr: $$('._2PQwXTA9rdVCZRcdlNWdEc').eq(0).text(),
							classification: $$('._2PQwXTA9rdVCZRcdlNWdEc').eq(1).text(),
						},
						tags: $$('._2MqejEqm9zjj4iIP-77ysf').text(),
						regions: [regionId]
					}

					// 爬取推荐餐厅
					if (result.restaurantInfo.url !== undefined) {
						totalInfoHandle.add({
							type: 1,
							url,
              regions:[]
						})

						try {
              await crawlRestaurant(host + result.restaurantInfo.url, {
                regions: []
              })
              totalInfoHandle.addSuccess({
                type: 1,
                url,
                regions:[]
              })
						} catch (err)  {
              logger.error(`crawl ineresting restaurant ${result.restaurantInfo.url} err`, err, url)
              totalInfoHandle.addError({
                type: 1,
                url,
								err
              })
							reject(err)
						}
					}

					// content
					$$('._198nXlXoiYBkCKbP5aX04J').children().each((k, v) => {
						let $v = $$(v)
						let tag = $v[0].tagName
						if (tag === 'p') {
							result.content.push({
								tag: 'p',
								text: $v.text()
							})
						}

						if (tag === 'h2') {
							result.content.push({
								tag: 'h2',
								text: $v.text()
							})
						}

						if (tag === 'figure') {
							if ($v.find('img').attr('src')) {
								result.content.push({
									tag: 'figure',
									src: $v.find('img').attr('src'),
									text: $v.find('img').attr('alt')
								})
							}
						}


						if (tag === 'div') {
							let imgs = []
							$$(v).find('figure').each((key, value) => {
								if ($$(value).find('img').attr('src')) {
									imgs.push({
										src: $$(value).find('img').attr('src'),
										text: $$(value).find('figcaption').text()
									})
								}
							})
							result.content.push({
								tag: 'div',
								imgs: imgs
							})
						}
					})
					Promise.all(
						[
							transPromise([result.title.text, result.title.intro, result.title.time], url), // title
							transPromise(result.restaurantInfo.classification, url), // classification
							transPromise(result.tags, url), // tags
							getContentTrans(result, url),
              crawlRestaurant(host + result.restaurantInfo.url, {
                regions: []
              })
						]
					).then(data => {
						result.title = {
							text: data[0][0],
							intro: data[0][1],
							time: data[0][2],
						}
						result.restaurantInfo.classification = data[1]
						result.tags = data[2]

						result.content = data[3]
						uploadInterestingImags(result)

						// let interesting = new Interesting(result, );
						// console.log('saving interesting...', result.url)

						Interesting.update({url: result.url}, result, {upsert: true}, function (err, res) {
							if (err) {
								reject(e, url)
							}
							else {
                resolve(url)
							}
						});
					}, err => {
						reject(err, url)
					})
				} catch (e) {
					reject(e, url)
				}
			}, err => {
				reject(err, url)
			})
  })

}
